package com.guoxue.action.front;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guoxue.domain.TapesRecordsVo;
import com.guoxue.domain.TapesShareVo;
import com.guoxue.domain.TotalInfoVo;
import com.guoxue.domain.DistrictVo;
import com.guoxue.domain.FollowsVo;
import com.guoxue.domain.UserVo;
import com.guoxue.model.RankModel;
import com.guoxue.model.RedisRecentUser;
import com.guoxue.model.RedisUser;
import com.guoxue.service.ITapesRecordsService;
import com.guoxue.service.ITapesShareService;
import com.guoxue.service.ITotalInfoService;
import com.guoxue.service.IAlbumService;
import com.guoxue.service.IDistrictService;
import com.guoxue.service.IFollowsService;
import com.guoxue.service.IUploadLogsService;
import com.guoxue.service.IUserDistrictService;
import com.guoxue.service.IUserService;
import com.guoxue.service.impl.TotalInfoServiceImpl;
import com.guoxue.util.RedisUtil;
import com.guoxue.util.ChatUtils;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.MD5Util;
import com.guoxue.util.OSSUtil;
import com.guoxue.util.OtherUtils;
import com.guoxue.util.PasswordUtil;

import redis.clients.jedis.Jedis;
/**
 * 
 * @author young
 *
 */
@Controller
@RequestMapping("Util")
public class UtilAction extends BaseAction{
	@Resource
	private OSSUtil oss;
	private static final String bucket = "bykj-gx-oss-bucket1";
	@Resource
	private ITapesRecordsService tapesService;
	@Resource
	private IUploadLogsService logService;
	@Resource
	private ITapesShareService shareService;
	@Resource
	private IUserService userService;
	@Resource
	private IAlbumService albumService;
	@Resource
	private IFollowsService followsService;
	@Resource
	private IDistrictService districtService;
	@Resource
	private IUserDistrictService userDistrictService;
	@Resource
	private ITapesRecordsService recoedService;
	@Resource
	private ITotalInfoService totalInfoService;
	
	@RequestMapping("/cleanTapes")
	@ResponseBody
	public JSON cleanTapesByTime(HttpServletRequest req, HttpServletResponse resp){
		Calendar c = Calendar.getInstance();
	    c.add(Calendar.MONTH, -1);
	    String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime());
	    List<TapesRecordsVo> tr = tapesService.findByTimeAndStatus(date); 
	    if (tr.size()!=0){
	    	for (TapesRecordsVo t:tr){
	    		oss.deleteObject(bucket, t.getTapes());
	    		tapesService.delete(t);
	    	}
	    }
		return null;
	}
	/**
	 * 
	 * @Description: 注册环信聊天账号（此方法是为了避免创建账号时注册环信账号失败，客户端再次调用该接口注册）
	 * @param: 
	 * @author:  
	 * @since: 2016年10月28日 下午5:17:26
	 */
	@RequestMapping("/createChatAccount")
	@ResponseBody
	public JSON createChatAccount(HttpServletRequest req, HttpServletResponse resp,Integer uid){
		UserVo user = userService.getUserByKey(uid);
		if (user==null){
			return Message(ERROR, "当前用户不存在", null);
		}
		ChatUtils.creatSinglUser(user.getId()+"", PasswordUtil.MD5Generator(user.getId()+"",user.getCreatedAt()), "GX"+user.getId());
		return Message(SUCCESS, "聊天账号注册成功", null);
	}
	
	/**
	 * 获取全局唯一key
	 * @param req
	 * @param resp
	 * @param uid
	 * @param type
	 * 			若为1：则检查用户照片上传是否超量
	 * @return
	 */
	@RequestMapping("/getKey")
	@ResponseBody
	public JSON getKey(HttpServletRequest req, HttpServletResponse resp, Integer uid, Integer type){
		if (uid==null){
			return Message(ERROR, "获取全局key失败，未提交用户id", null);
		} 
		if (type!=null){
			if (type==1){
				int c = 0;
				c = albumService.countAlbumByUid(uid);
				if (c>=10){
					return Message(ERROR, "个人相册数量已达10张", null);
				}
			}
		}
		//-----type为1是检查用户是否有上传资格
		return Message(SUCCESS, "获取全局key成功", MD5Util.generatorKey(uid));
	}
	/**
	 * 收听计数
	 * @param req
	 * @param resp
	 * @param uid
	 * @param tapesId
	 * @return
	 */
	@RequestMapping("listenCount")
	@ResponseBody
	public JSON listenCount(HttpServletRequest req, HttpServletResponse resp, Integer uid, Integer tapesId){
		if (uid==null){
			return Message(ERROR, "未提交用户id", null);
		}
		if (tapesId==null){
			return Message(ERROR, "未提交音频id", null);
		}
		Jedis jedis = RedisUtil.getJedis();
		RedisUser redisUser =(RedisUser) RedisUtil.unserialize(jedis.get((tapesId+"R"+uid).getBytes()));
		int destroy = OtherUtils.subtractDate(new Date());
		boolean boo = false;
		if (redisUser==null){
			redisUser = new RedisUser();
			boo = true;
		}else if (redisUser.getCount()<3){
			boo = true;
		} else {
			return Message(ERROR, "当日收听计数次数已达上限", null);
		}
		if (boo) {
			TapesShareVo share = shareService.getTapesShareByTid(tapesId, 0);
			if (share==null){
				share = new TapesShareVo();
				share.setTapesId(tapesId);
				share.setTotalListend(1);
				share.setWeeklyListend(1);
				share.setWeeklyTotalListend(1);
			} else {
				share.setTotalListend(share.getTotalListend()+1);
				share.setWeeklyListend(share.getWeeklyListend()+1);
				share.setWeeklyTotalListend(share.getWeeklyTotalListend()+1);
			}
			redisUser.setCount(redisUser.getCount()+1);
			shareService.saveTapesShare(share);
			TotalInfoVo totalInfo = totalInfoService.getInfoByUid(uid);
			if(totalInfo==null){
				totalInfo = new TotalInfoVo();
				totalInfo.setUid(uid);
				totalInfo.setListened(1);
			} else {
				totalInfo.setListened(totalInfo.getListened()+1);
			}
			totalInfoService.saveOrUpateInfo(totalInfo);
			jedis.setex((tapesId+"R"+uid).getBytes(), destroy,RedisUtil.serialize(redisUser));
		}
		//添加最近听众
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		SimpleDateFormat df = new SimpleDateFormat("yMMddHHmms");
        c.add(Calendar.DAY_OF_MONTH, 30);
		List<RedisRecentUser> redisRecentUserList =(List<RedisRecentUser>) RedisUtil.unserialize(jedis.get((tapesId+"L").getBytes()));
		if(null == redisRecentUserList){
			redisRecentUserList = new ArrayList<>();
		}
		UserVo user = userService.getUserByKey(uid);
		String uidImgUrl = user.getImgUrl();
		RedisRecentUser redisRecentUser = new RedisRecentUser();
		redisRecentUser.setId(uid);
		if(null != uidImgUrl && !"".equals(uidImgUrl)){
			//redisRecentUser.setImgUrl(oss.getUrl(bucket, uidImgUrl, new Date(new Date().getTime() + 3600 * 1000 * 24 * 30)));
			redisRecentUser.setImgUrl(uidImgUrl);
		}
		//redisRecentUser.setDate(df.format(new Date()));
		redisRecentUserList.add(redisRecentUser);
		//设置过期时间
		jedis.set((tapesId+"L").getBytes(), RedisUtil.serialize(redisRecentUserList));
		jedis.expireAt((tapesId+"L").getBytes(), c.getTime().getTime()/1000);
		jedis.close();
		return Message(SUCCESS, "SUCCESS", null);
	}
/*	*//**
	 * 存放新浪、QQ等第三方Token接口
	 * @param req
	 * @param resp
	 * @param uid
	 * 			用户id
	 * @param token
	 * 			所获取到的token
	 * @param type
	 * 			token所属类型  
	 * @return
	 *//*
	@RequestMapping("/SaveToken")
	@ResponseBody
	public JSON saveToken(HttpServletRequest req, HttpServletResponse resp, String userId,Integer type, Integer uid,String otherName){
		if (uid==null){
			return Message(ERROR, "系统uid为空", null);
		}
		if (type==null){
			return Message(ERROR, "token类型未提交或为空", null);
		}
		if (isEmpty(otherName)){
			return Message(ERROR, "第三方应用昵称为空", null);
		}
		if (userId==null){
			return Message(ERROR, "第三方用户id为空", null);
		}
		OtherUsersVo tv = otherUsersService.getTokenByUidAndType(uid,type);
		if (tv == null){
			tv = new OtherUsersVo();
			tv.setUserId(userId);
			tv.setType(type);
			tv.setUid(uid);
			tv.setOtherName(otherName);
			otherUsersService.saveToken(tv);
		}
		return Message(SUCCESS, "存放用户成功", null);
	}*/
	/**
	 * 全站模糊查找好友
	 * @param req
	 * @param resp
	 * @param param
	 * 			手机号、国学吧号、昵称
	 * @return
	 */
	@RequestMapping("/searchFromApp")
	@ResponseBody
	public JSON searchFromApp(HttpServletRequest req, HttpServletResponse resp,String param, Integer uid){
		try{
		if (uid==null){
			return Message(ERROR, "未提交uid", null);
		}
		if (param==null){
			return Message(ERROR, "未提交搜索字段", null);
		}
		UserVo self = userService.getUserByKey(uid);
		String selfNickName= self.getNickName();
		String selfTel = self.getUserTel();
		UserVo user = null;
		JSONArray array = new JSONArray();
		if (OtherUtils.isMobileNO(param)){
			if (selfTel.equals(param)){
				return Message(ERROR, "这不是你自己吗？", null);
			}
			user = userService.getUserByTel(param);
		}
		if (OtherUtils.isNumber(param)&&!OtherUtils.isMobileNO(param)){
			if (uid==Integer.parseInt(param)){
				return Message(ERROR, "这不是你自己吗？", null);
			}
			user = userService.getUserByKey(Integer.parseInt(param));
		} 
		if (user!=null){
			JSONObject obj = new JSONObject();
			obj.put("nickName", user.getNickName());
			obj.put("sex", user.getSex());
			obj.put("signature", isEmpty(user.getPersonSignature())?null:user.getPersonSignature());
			obj.put("headUrl",  isEmpty(user.getImgUrl())?null:oss.getUrl(bucket, user.getImgUrl(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
			obj.put("uid", user.getId());
			FollowsVo follow = followsService.getFriendById(user.getId(), uid,0);
			if (follow==null){
				obj.put("followed", false);
			}else{
				obj.put("followed", true);
			}
			array.add(obj);
		} else {
			if (selfNickName.equals(param)){
				return Message(ERROR, "这不是你自己吗？", null);
			}
			List<UserVo> users = userService.getUserLikeNickname(param);
			if (users.size()>0){
				for(UserVo us:users){
					JSONObject o = new JSONObject();
					o.put("nickName", us.getNickName());
					o.put("sex", us.getSex());
					o.put("signature", isEmpty(us.getPersonSignature())?null:us.getPersonSignature());
					o.put("headUrl",  isEmpty(us.getImgUrl())?null:oss.getUrl(bucket, us.getImgUrl(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
					o.put("uid", us.getId());
					FollowsVo follow = followsService.getFriendById(us.getId(), uid,0);
					if (follow==null){
						o.put("followed", false);
					}else{
						o.put("followed", true);
					}
					array.add(o);
				}
			}
		}
		return Message(SUCCESS, "查询用户成功", array.size()>0?array:null);
		}catch (Exception e) {
			LoggerUtil.logInfo(e, "查询异常");
		}
		return null;
	}
	/**
	 * 获取对应地区学校列表
	 * @param req
	 * @param resp
	 * @param city
	 * 			城市
	 * @param province
	 * 			省份
	 * @param county
	 * 			区县
	 * @return
	 */
	@RequestMapping("/getSchool")
	@ResponseBody
	public JSON getSchool(HttpServletRequest req, HttpServletResponse resp,String city, String province, String county){
		if (isEmpty(city)){
			return Message(ERROR, "未提交城市", null);
		}
		if (isEmpty(province)){
			return Message(ERROR, "未提交省份", null);
		}
		if (isEmpty(county)){
			return Message(ERROR, "未提交区县", null);
		}
		List<DistrictVo> dl = districtService.getSchoolList(city,province,county);
		JSONArray array = new JSONArray();
		if (dl.size()>0){
			for(DistrictVo d:dl){
				array.add(d.getSchool());
			}
		}
		return Message(SUCCESS, "获取学校成功", array.size()>0?array:"");
	}
	/**
	 * 获取本地排行
	 * @param req
	 * @param resp
	 * @param uid
	 * 		 	当前用户id
	 * @param type
	 * 			1：本地人气榜 2：本地实力榜  3:本地周人气榜 ，4: 本地周实力榜
	 * @return
	 */
	@RequestMapping("getLocalRank")
	@ResponseBody
	public JSON getLocalRank(HttpServletRequest req, HttpServletResponse resp,Integer uid,Integer type){
		if (type>4){
			return Message(ERROR, "位置type类型", null);
		}
		if (uid==null){
			return Message(ERROR, "未提交用户id", null);
		}
		UserVo user = userService.getUserByKey(uid);
		if (user==null){
			return Message(ERROR, "用户不存在", null);
		}
		if (user.getDistrict()==0){
			return Message(No_Bind, "请先绑定区域", null);
		}
		List<RankModel> trs = new ArrayList<RankModel>();
		if (type==1){
			trs = recoedService.getLocalGift(user.getDistrict(),type);
		}
		if (type==2){
			trs = recoedService.getLocalGift(user.getDistrict(),type);
		}
		if (type==3){
			trs = recoedService.getLocalWeekly(user.getDistrict(),type);
		}
		if (type==4){
			trs = recoedService.getLocalWeekly(user.getDistrict(),type);
		}
		if (trs==null||trs.size()==0){
			return Message(ERROR, "当前暂无数据", null);
		}
		if (trs!=null&&trs.size()>0){
			for(RankModel r:trs){
				r.setImgUrl(oss.getUrl(bucket, r.getImgUrl(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			return Message(SUCCESS, "获取成功", trs);
		}else{
			return Message(ERROR, "暂无数据", null);
		}
	}
	/**
	 * 全国榜单
	 * @param req
	 * @param resp
	 * @param type
	 * 			1：全国人气榜 2：全国实力榜 , 3:全国周人气帮 ，4：全国周实力榜
	 * @return
	 */
	@RequestMapping("getTotalRank")
	@ResponseBody
	public JSON getTotalRank(HttpServletRequest req, HttpServletResponse resp,Integer type){
		if (type==null){
			return Message(ERROR, "未指定类型", null);
		}
		if (type>4){
			return Message(ERROR, "位置type类型", null);
		}
		List<RankModel> trs = new ArrayList<RankModel>();
		if (type==1){
			trs = recoedService.getTotalGift(type);
		}
		if (type==2){
			trs = recoedService.getTotalGift(type);
		}
		if (type==3){
			trs = recoedService.getTotalWeeklyGift(type);
		}
		if (type==4){
			trs = recoedService.getTotalWeeklyGift(type);
		}
		if (trs!=null&&trs.size()>0){
			for(RankModel r:trs){
				r.setImgUrl(oss.getUrl(bucket, r.getImgUrl(), new Date(new Date().getTime() + 3600 * 1000 * 12)));
			}
			return Message(SUCCESS, "获取成功", trs);
		}else{
			return Message(ERROR, "暂无数据", null);
		}
		
	}
	
	
}
